package api

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"yun_image/config/api"
	"yun_image/config/user"
	"yun_image/entity"
	"yun_image/service"
	"yun_image/util"
)

const (
	loginPath          = api.LoginPath
	registerPath       = api.RegisterPath
	updateUserPath     = api.UpdateUserPath
	getUserByTokenPath = api.GetUserByTokenPath
	stateOk            = user.StateOk
)

// 如果账号或密码错误，返回一个零值user
func login(context *gin.Context) {
	account := context.PostForm("account")
	password := context.PostForm("password")
	if account == "" || password == "" {
		context.String(http.StatusInternalServerError, "")
		return
	}
	var user entity.User
	err := service.Login(&user, account, password)
	if err != nil {
		context.String(http.StatusInternalServerError, err.Error())
		return
	}
	context.JSON(http.StatusOK, user)
}

// 如果该账户已存在，返回一个零值user
func register(context *gin.Context) {
	account := context.PostForm("account")
	password := context.PostForm("password")
	userName := context.PostForm("userName")
	if account == "" || password == "" || userName == "" {
		context.String(http.StatusInternalServerError, "")
		return
	}
	var user entity.User
	err := service.Register(&user, account, password, userName)
	if err != nil {
		context.String(http.StatusInternalServerError, err.Error())
		return
	}
	context.JSON(http.StatusOK, user)
}

// 用户更新个人信息，目前只能更新userName和profilePicture
func updateUser(context *gin.Context) {
	var user entity.User
	userVal, _ := context.Get("user")
	user, _ = userVal.(entity.User)
	user.UserName = context.DefaultPostForm("userName", user.UserName)
	user.ProfilePicture = context.DefaultPostForm("profilePicture", user.ProfilePicture)

	err := service.UpdateUser(&user)
	if err != nil {
		context.String(http.StatusInternalServerError, "")
	} else {
		context.JSON(http.StatusOK, gin.H{
			"success": true,
		})
	}
}
func getUserByToken(context *gin.Context) {
	token := context.GetHeader("token")
	var user entity.User
	err := service.GetUserByToken(&user, token)
	if err != nil {
		context.String(http.StatusInternalServerError, "")
	} else {
		context.JSON(http.StatusOK, user)
	}
}

func getCaptcha(context *gin.Context) {
	var captcha util.Captcha
	id, base64String, err := captcha.CreateCode("digit")
	if err != nil {
		context.String(http.StatusInternalServerError, "")
	} else {
		context.JSON(http.StatusOK, gin.H{
			"id":           id,
			"base64String": base64String,
		})
	}
}

func verifyCaptcha(context *gin.Context) {
	answer := context.PostForm("answer")
	id := context.PostForm("id")
	var captcha util.Captcha
	result := captcha.VerifyCaptcha(id, answer)
	context.JSON(http.StatusOK, gin.H{
		"success": result,
	})
}

func startUserApi() {
	router.POST(loginPath, login)
	router.POST(registerPath, register)
	router.POST(updateUserPath, updateUser)
	router.POST(getUserByTokenPath, getUserByToken)
	router.POST(api.GetCaptchaPath, getCaptcha)
	router.POST(api.VerifyCaptchaPath, verifyCaptcha)
}
